import 'dart:convert';

import 'package:client/common/fun.dart';
import 'package:dio/dio.dart';
import 'package:client/model/user_model.dart';
import 'package:client/provider/app_provider.dart';

class MyHttp {
  static String urlReg = "/reg";
  static String urlLogin = "/login";
  static String urlChagenPwd = "/change_pwd";

  static final Dio _http = Dio(BaseOptions(
    baseUrl: AppProvider.getConfig().httpHost,
    // baseUrl: "http://localhost:22222",
    connectTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
  ));

  static Dio instance() {
    return _http;
  }

  static httpToken(String token) {
    _http.options.headers["token"] = token;
  }

  static post(String url, Map data) async {
    try {
      var http = instance();
      var dataStr = json.encode(data);
      print("post data");
      print(url);
      print(dataStr);
      var resp = await http.post<String>(url, data: dataStr);
      print("resp");
      print(resp.data.runtimeType);
      print(resp);
      var respMap = json.decode(resp.data as String);
      return respMap;
    } on DioException catch (e) {
      print(e);
      if (e.response != null) {
        print("aaa");
        print(e.response?.data);
        print(e.response?.headers);
        print(e.response?.requestOptions);
      } else {
        print(e.requestOptions);
        print(e.message);
      }
    }
    Fun.dialog("错误", "网络请求失败");
    return null;
  }

  static reg(Map data) async {
    var respMap = await post(MyHttp.urlReg, data);
    if (respMap != null) {
      if (respMap["code"] == 0) {
        var rtData = respMap["data"];
        var m = UserModel();
        m.name = rtData["name"];
        m.uuid = rtData["uuid"];
        m.token = rtData["token"];
        AppProvider.setUser(m);
      } else {
        Fun.dialog("错误", respMap["msg"]);
      }
      return respMap;
    }
  }

  static login(Map data) async {
    var respMap = await post(MyHttp.urlLogin, data);
    if (respMap != null) {
      if (respMap["code"] == 0) {
        // success(respMap);
        var rtData = respMap["data"];
        var m = UserModel();
        m.name = rtData["name"];
        m.uuid = rtData["uuid"];
        m.token = rtData["token"];
        AppProvider.setUser(m);
      } else {
        Fun.dialog("错误", respMap["msg"]);
      }
    }
  }

  static Future<void> changePwd(Map data) async {
    var respMap = await post(MyHttp.urlChagenPwd, data);
    if (respMap != null) {
      if (respMap["code"] == 0) {
        Fun.dialog("", "修改成功");
      } else {
        Fun.dialog("错误", respMap["msg"]);
      }
    }
  }
}
